package com.example.chirdrenserver.Service.UserService.Impl;


import cn.hutool.core.bean.BeanUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.example.chirdrenserver.Holder.UserHolder;
import com.example.chirdrenserver.Pojo.dto.CommentQueryDTO;
import com.example.chirdrenserver.Pojo.dto.PostCommentDTO;
import com.example.chirdrenserver.Pojo.dto.ReCommentDTO;
import com.example.chirdrenserver.Pojo.entity.Comment;
import com.example.chirdrenserver.Service.UserService.CommentService;
import com.example.chirdrenserver.exception.BaseException;
import com.example.chirdrenserver.mapper.CommentMapper;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;
import java.util.Collection;
import java.util.List;
import java.util.Locale;

/**
 * @Author: Yu
 * @CreateTime: 2025-07-04
 * @Description:
 */
@Service
public class CommentServiceImpl extends ServiceImpl<CommentMapper, Comment> implements CommentService {
    @Override public void postComment(PostCommentDTO postCommentDTO) {
        Comment comment=new Comment();
        comment.setCreateTime(LocalDateTime.now());
        comment.setParentCommentId(Long.valueOf(1));
        comment.setUserId(UserHolder.get());
        BeanUtils.copyProperties(postCommentDTO,comment);
        save(comment);
    }

    @Override public void ReComment(ReCommentDTO reCommentDTO) {
        Comment comment=new Comment();
        Comment parent = getOne(new LambdaQueryWrapper<Comment>().eq(Comment::getCommentId, reCommentDTO.getParentId()));
        if(BeanUtil.isEmpty(parent))
        {
            throw new BaseException("回复评论不存在");
        }
        comment.setPostId(parent.getPostId());
        comment.setCreateTime(LocalDateTime.now());
        comment.setParentCommentId(reCommentDTO.getParentId());
        comment.setUserId(UserHolder.get());
        BeanUtils.copyProperties(reCommentDTO,comment);
        save(comment);
    }

    @Override
    public List<Comment> getComment(CommentQueryDTO commentQueryDTO) {
        // 创建正确类型的分页对象
        Page<Comment> pageParam = new Page<>(
                commentQueryDTO.getCurrentPage(),
                commentQueryDTO.getPageSize()
        );

        // 构建查询条件
        LambdaQueryWrapper<Comment> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(Comment::getPostId, commentQueryDTO.getPostId());

        // 执行分页查询
        IPage<Comment> result = this.page(pageParam, queryWrapper);

        return result.getRecords();
    }
}
